/**
 * 递归转换菜单
 * parentId list => children tree
 */
export const rawList2Tree = (arrList: IObj[], parentIdKey: string, childKey: string, pid?: string) => {
    if (arrList.length === 0) {
        return []
    }    
	return arrList
        .filter((item) =>
            // 如果没有父id（第一次递归的时候）将所有父级查询出来
            // 这里认为 !item[parentIdKey] 是最顶层
            pid ? item[parentIdKey] === pid : !item[parentIdKey]
        )
        .map((item) => {
            // 通过父节点ID查询所有子节点
            item[childKey] = rawList2Tree(arrList, parentIdKey, childKey, item.id)
            return item
        })
}

/**
 * 递归转换菜单
 * parentId list => children tree
 */
export const rawList2Tree2 = (arrList: IObj[], parentIdKey: string = 'parentId', childKey: string = 'children') => {
    if (arrList.length === 0) {
        return []
    }

    let menuTree: IObj[] = []

    !function Recursion(pid?: string) {
        const tempArr: IObj[] = []
        // tslint:disable-next-line:prefer-for-of
        for (let index = 0; index < arrList.length; index++) {
            const item = arrList[index]
            // 如果没有父id（第一次递归的时候）将所有父级查询出来
            // 这里认为 !item[parentIdKey] 是最顶层
            if (pid ? item[parentIdKey] === pid : !item[parentIdKey]) {
                // 通过父节点ID查询所有子节点
                item[childKey] = Recursion(item.id)
                tempArr.push(item)
            }
        }
        if (!pid) {
            menuTree = tempArr
        }
        return tempArr
    }()

    return menuTree
}

/**
 * 递归转换
 * children tree =>  parentId list
 */
export const tree2RawList = (treeData: IObj[], idKey: string = 'id', parentIdKey: string = 'parentId', childKey: string = 'children') => {
    if (treeData.length === 0) {
        return []
    }
    let copyTreeData = JSON.parse(JSON.stringify(treeData))
    let rawList: IObj[] = [];

    (function Recursion(prevList: IObj[], pid: any = null) {

        const concatList = prevList.map((item: IObj) => {
            if (item[childKey] && item[childKey].length) {
                Recursion(item[childKey], item[idKey])
                delete item[childKey]
            }
            item[parentIdKey] = pid
            return item
        })

        rawList = rawList.concat(concatList)
    })(copyTreeData)

    return rawList
}